'use strict';
const path = require('path')
const Controller = require('egg').Controller;

const { saveFile, readFile, delFile } = require('./../../utils/fs-extend')

class BookletController extends Controller {
  //@GET booklet/:booklet_id/sections
  async getBookletSections() {
    const { ctx, service } = this;
    const { Response, params } = ctx
    const res = new Response()
    try {
      const { booklet_id } = params //user_id
      let booklet = await service.booklet.find(booklet_id)
      booklet = booklet.toJSON()
      const sections = await service.section.getSectionsByBookletId(booklet_id)
      booklet.sections = sections
      res.data = {
        booklet
      }
    }catch(e) {
      console.log(e.message)
			res.status = ctx.STATUS.ERROR;
			res.message = ctx.CODE.Unauthorized + '： ' + e;
    }
    ctx.body = res
  }

  //上传文件及其字段，进行新插入树
  async create() {
    const { ctx, service } = this;
    const { Response, ResponseError, request: { body } } = ctx
    const res = new Response() //作为响应
    try {
      const booklets = body
      const baseBookletDir = 'app/public/booklets/'
      const coverImageUrlsPath = 'app/public/json'
      const coverImageUrls = JSON.parse(readFile(coverImageUrlsPath, 'booklets_cover_url.json')) 
      let importCount = 0
      for(let name in booklets) {
        const sections = booklets[name] // 章节
        const hasBookletExisted = !!(await service.booklet.findBookletByName(name))
        if(hasBookletExisted) continue //已经存在，直接退出

        const uploadpath = await service.uploadPath.create({ //新建一条上传路径记录
          value: baseBookletDir + name
        })
        const booklet = await service.booklet.create({//新建一条书的记录
          name, cover_url: coverImageUrls[uploadpath.id]
        })
        const { id: upload_path_id } = uploadpath
        const { id: booklet_id } = booklet
        for(let section of sections) {
          const { serialNumber, sectionName, suffix } = section
          const file = await service.file.create({
            upload_path_id, mime_type: 'text/markdown', filename: serialNumber+'-'+sectionName+'.'+suffix,
          })
          await service.section.create({
            booklet_id, serial_number: +serialNumber, file_id: file.id, name: sectionName
          })
        }
        importCount++//成功导入一本
      }
      res.message = importCount + '本导入成功，本数不对说明书库已经存在'
    }catch(e) {
      console.log(e)
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }
}

module.exports = BookletController;
